package com.clayecloud.module_visitor.viewModels;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.clayecloud.lib_common.apis.VisitorApi;
import com.clayecloud.lib_common.utils.GsonUtil;
import com.clayecloud.lib_common.utils.HttpUtil;
import com.clayecloud.lib_common.utils.LoginUtil;
import com.clayecloud.lib_common.utils.MessageUtil;
import com.clayecloud.module_visitor.entity.Visitor;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class VisitorListViewModel extends ViewModel {

    private VisitorApi visitorApi;

    private MutableLiveData<List<Visitor>> visitors;

    public MutableLiveData<List<Visitor>> getVisitors() {
        return visitors;
    }

    public void setVisitors(MutableLiveData<List<Visitor>> visitors) {
        this.visitors = visitors;
    }

    public void leaddata(){
        visitorApi = HttpUtil.getInstance().create(VisitorApi.class);
        MutableLiveData<List<Visitor>> visitors = new MutableLiveData<>();
        visitors.setValue(new ArrayList<>());
        setVisitors(visitors);
        initListData();
    }

    private void initListData() {
        visitorApi.select(LoginUtil.getUserID())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<MessageUtil>() {
                    private Disposable disposable;
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(@NonNull MessageUtil messageUtil) {
                        List<Visitor> visitors = GsonUtil.getInstance().fromJson(GsonUtil.getInstance().toJson(messageUtil.getObj()),new TypeToken<List<Visitor>>() {}.getType());
                        MutableLiveData<List<Visitor>> mutableLiveData = getVisitors();
                        mutableLiveData.setValue(visitors);
                        setVisitors(mutableLiveData);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("VisitorListViewModel initListData error",e.getMessage());
                        disposable.dispose();
                    }

                    @Override
                    public void onComplete() {
                        disposable.dispose();
                    }
                });
    }


}
